﻿using DevExpress.XtraEditors.Repository;
using DevTeam;
using Manina.Windows.Forms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Aksesuar
{
    public partial class Resimler : XPopupForm
    {
        string idxs = string.Empty;
        public Resimler(string idxs)
            : this()
        {
            this.idxs = idxs;
        }

        public Resimler()
        {
            InitializeComponent();


            //Application.Idle += new EventHandler(Application_Idle);

            // Populate renderer dropdown
            //Assembly assembly = Assembly.GetAssembly(typeof(ImageListView));
            //int i = 0;
            //foreach (Type t in assembly.GetTypes())
            //{
            //    if (t.BaseType == typeof(Manina.Windows.Forms.ImageListView.ImageListViewRenderer))
            //    {
            //        renderertoolStripComboBox.Items.Add(new RendererItem(t));
            //        if (t.Name == "DefaultRenderer")
            //            renderertoolStripComboBox.SelectedIndex = i;
            //        i++;
            //    }
            //}


            imageListView1.SetRenderer(new DemoRenderer());

            //imageListView1.Items.AddRange(Directory.GetFiles(folder, "*.JPG"));
        }

        string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\CEAks";
        private void Resimler_Load(object sender, EventArgs e)
        {
            
            imageListView1.ItemClick += imageListView1_ItemClick;

            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            //TOOD: dizini boşalt (hergün?)

            GetStatus();

            //TODO: ViewMode, Thumbnail Size, Category, Series ekliyorum ama kayboluyor! ofisteki PC'de dene..
            barEditItem9.EditValueChanged += barEditItem9_EditValueChanged;
            barEditItem6.EditValueChanged += barEditItem6_EditValueChanged;
            barEditItem7.EditValueChanged += barEditItem7_EditValueChanged;
            barEditItem8.EditValueChanged += barEditItem8_EditValueChanged;
            ((RepositoryItemComboBox)barEditItem6.Edit).Items.AddRange(new object[] { "Details", "Thumbnails", "Gallery", "Pane" });
            barEditItem6.EditValue = "Pane";

            ((RepositoryItemComboBox)barEditItem7.Edit).Items.AddRange(new object[] { 120, 150, 200 });
            barEditItem7.EditValue = 120;

            ((RepositoryItemGridLookUpEdit)barEditItem9.Edit).Assign(RI(Rp.ProductCategory));

            ((RepositoryItemComboBox)barEditItem8.Edit).Items.AddRange(Seri.ToArray());
            ((RepositoryItemComboBox)barEditItem8.Edit).TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;


            if (idxs != string.Empty)
                List();
        }

        DataTable dtA;

        void barEditItem7_EditValueChanged(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(barEditItem7.EditValue.ToInt(), barEditItem7.EditValue.ToInt());
        }

        void barEditItem6_EditValueChanged(object sender, EventArgs e)
        {
            switch (barEditItem6.EditValue.ToString())
            {
                case "Details": imageListView1.View = Manina.Windows.Forms.View.Details; break;
                case "Thumbnails": imageListView1.View = Manina.Windows.Forms.View.Thumbnails; break;
                case "Gallery": imageListView1.View = Manina.Windows.Forms.View.Gallery; break;
                case "Pane": imageListView1.View = Manina.Windows.Forms.View.Pane; break;
            }
        }

        bool started = false;
        void barEditItem8_EditValueChanged(object sender, EventArgs e)
        {
            if (!started)
            {
                try
                {
                    started = true;
                    barEditItem9.EditValue = null;
                    List();
                }
                finally
                {
                    started = false;
                }
            }
        }

        void barEditItem9_EditValueChanged(object sender, EventArgs e)
        {
            if (!started)
            {
                try
                {
                    started = true;
                    barEditItem8.EditValue = null;
                    List();
                }
                finally
                {
                    started = false;
                }
            }
        }


        #region A Custom Renderer for Demonstrating the Control
        /// <summary>
        /// A renderer that displays useful information
        /// when the control is empty.
        /// </summary>
        private class DemoRenderer : ImageListView.ImageListViewRenderer
        {
            public DemoRenderer()
            {
            }

            public override void Dispose()
            {
                base.Dispose();
            }

            /// <summary>
            /// Initializes the System.Drawing.Graphics used to draw
            /// control elements.
            /// </summary>
            /// <param name="g">The System.Drawing.Graphics to draw on.</param>
            public override void InitializeGraphics(Graphics g)
            {
                base.InitializeGraphics(g);
                g.SmoothingMode = SmoothingMode.HighQuality;
            }

        }
        #endregion

        #region Switch Renderers
        private struct RendererItem
        {
            public Type Type;

            public override string ToString()
            {
                return Type.Name;
            }

            public RendererItem(Type type)
            {
                Type = type;
            }
        }

        //private void renderertoolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    // Change the renderer
        //    Assembly assembly = Assembly.GetAssembly(typeof(ImageListView));
        //    RendererItem item = (RendererItem)renderertoolStripComboBox.SelectedItem;
        //    ImageListView.ImageListViewRenderer renderer = assembly.CreateInstance(item.Type.FullName) as ImageListView.ImageListViewRenderer;
        //    imageListView1.SetRenderer(renderer);
        //    imageListView1.Focus();
        //}
        #endregion

        #region Update Status Bar
        private void imageListView1_ThumbnailCached(object sender, ThumbnailCachedEventArgs e)
        {
            // This event is fired after a new thumbnail is cached.
            Notify(string.Format("Cached image: {0}", e.Item.Text));
        }

        private void imageListView1_SelectionChanged(object sender, EventArgs e)
        {
            UpdateStatus();
        }

        private void UpdateStatus()
        {
            if (imageListView1.Items.Count == 0)
                Notify("Ready");
            else if (imageListView1.SelectedItems.Count == 0)
                Notify(string.Format("{0} images", imageListView1.Items.Count));
            else
                Notify(string.Format("{0} images ({1} selected)", imageListView1.Items.Count, imageListView1.SelectedItems.Count));
        }
        #endregion

        #region Modify Column Headers
        private void columnsToolStripButton_Click(object sender, EventArgs e)
        {
            //ChooseColumns form = new ChooseColumns();
            //form.imageListView = imageListView1;
            //form.ShowDialog();
        }
        #endregion


        private void clearCacheToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.ClearThumbnailCache();
        }

        #region Rotate Selected Images
        private void rotateCCWToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Rotating will overwrite original images. Are you sure you want to continue?",
                "ImageListViewDemo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                foreach (ImageListViewItem item in imageListView1.SelectedItems)
                {
                    item.BeginEdit();
                    using (Image img = Image.FromFile(item.FileName))
                    {
                        img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        img.Save(item.FileName);
                    }
                    item.Update();
                    item.EndEdit();
                }
            }
        }

        private void rotateCWToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Rotating will overwrite original images. Are you sure you want to continue?",
                "ImageListViewDemo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                foreach (ImageListViewItem item in imageListView1.SelectedItems)
                {
                    item.BeginEdit();
                    using (Image img = Image.FromFile(item.FileName))
                    {
                        img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        img.Save(item.FileName);
                    }
                    item.Update();
                    item.EndEdit();
                }
            }
        }
        #endregion




        List<string> Seri = new List<string>();

        string GetFN(string fileName)
        {
            return System.IO.Path.GetFileNameWithoutExtension(fileName);
        }

        void GetStatus()
        {
            DataTable dt = Session.DataManager.ExecuteDataTable("GetAksSira");
            foreach (DataRow r in dt.Rows)
            {
                string Se = r["AksSeriId"].ToString();

                if (Se != "0")
                    if (!Seri.Contains(Se))
                        Seri.Add(Se);
            }
            Seri.Sort();


            //cmbKat.Items.AddRange(Kat.ToArray());
            //cmbSeri.Items.AddRange(Seri.ToArray());
        }

        List<string> files;
        void List()
        {
            //Before clearing items call:
            imageListView1.SuspendLayout();

            imageListView1.Items.Clear();
            files = new List<string>();
            //string folder = @"D:\AksPhoto.Cropped";

            int KategoriId = barEditItem9.EditValue.ToInt();
            int SeriId = barEditItem8.EditValue.ToInt();
            if (KategoriId > 0 || SeriId > 0)
                idxs = string.Empty;
            dtA = ExecuteDataTable("GetAksPhoto2", KategoriId, SeriId, idxs);

            foreach (DataRow r in dtA.Rows)
            {
                string filename = r["AksesuarId"].ToString() /*+ ".JPG"*/;
                string Path = folder + "\\" + filename;

                FileManager.Write(filename,(byte[])r["Photo2"]);
                
                files.Add(filename);
            }

            //Directory.GetFiles(folder, "*.JPG")
            imageListView1.Items.AddRange(files.ToArray());

            //when you are done adding items call:
            imageListView1.ResumeLayout();

        }

        void imageListView1_ItemClick(object sender, ItemClickEventArgs e)
        {
            /*
            string Sr = Path.GetFileNameWithoutExtension(e.Item.FileName);
            using (DetailA da = new DetailA(intParse(Sr)))
                da.ShowDialog();
             */
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }

        /*
        void YARDIMCI_btnCrop_Click(object sender, EventArgs e)
        {            
            //foreach (string fileName in Directory.GetFiles(newDirectory))
            //{
            //    byte[] content = ReadBitmap2ByteArray(fileName);
            //    string Sr = Path.GetFileNameWithoutExtension(fileName);
            //    StoreBlob2DataBase(Sira[Sr].AksesuarId, content);
            //}

            //MessageBox.Show("Done.");
            //return;

            
            
            
            foreach (string fileName in Directory.GetFiles(targetDirectoryR))
                using (StreamReader reader = new StreamReader(fileName))
                {
                    string[] r = reader.ReadLine().Split(",".ToCharArray());
                    string id = GetFN(fileName);

                    listR.Add(id, new Rectangle(int.Parse(r[0]), int.Parse(r[1]), int.Parse(r[2]), int.Parse(r[3])));
                }


            for (int i = 0; i < listF.Count; i++)
            {
                string idx = listF[i];
                {
                    FileStream fs = new FileStream(targetDirectory + "\\" + listF[i] + ".JPG", FileMode.Open, FileAccess.Read);
                    //using (Image img = Image.FromFile(targetDirectory + "\\" + idx + ".JPG"))
                    using (Image objImage = System.Drawing.Image.FromStream(fs))
                    {

                        Rectangle cR = listR[idx];
                        cR.Inflate(3, 3);   //listR[idx]'yi 2'şer pixel genişlet her yönde!

                        KalikoImage sharpimg = new KalikoImage(Crop(objImage, cR));
                        //sharpimg = sharpimg.Scale(new FitScaling(32, 32));
                        sharpimg.Resize(sharpimg.Width / 2, sharpimg.Height / 2);
                        sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2F, 0.5F, 20));   //threshold: http://www.damiensymonds.com.au/tut_usm.html
                        sharpimg.SaveJpg(newDirectory + "\\" + idx + ".JPG", 90);
                        sharpimg.Dispose();

                        fs.Close();
                        fs.Dispose();
                    }
                    //float hue;
                    //using (FileStream s = new FileStream(newDirectory + "\\" + idx + ".JPG", FileMode.Open))
                    //{
                    //    Bitmap img = (Bitmap)Image.FromStream(s);
                    //    if (img != null)
                    //    {
                    //        hue = GetDominantColor(img).GetHue();
                    //        using (StreamWriter writer = new StreamWriter(hueDirectory + "\\" + idx + ".txt", true))
                    //        {
                    //            writer.WriteLine(hue);
                    //        }
                    //    }
                    //}
                }
            }
            MessageBox.Show("Done.");
        }



        public Color GetDominantColor(Bitmap image)
        {
            if (image != null)
            {
                BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0,
                                         image.Width, image.Height),
                                         ImageLockMode.ReadOnly,
                                         PixelFormat.Format32bppArgb);

                int a = 0, r = 0, g = 0, b = 0;
                unsafe
                {
                    byte* imagePointer1 = (byte*)bitmapData1.Scan0;
                    for (int i = 0; i < bitmapData1.Height; i++)
                    {
                        for (int j = 0; j < bitmapData1.Width; j++)
                        {
                            a++;
                            b += imagePointer1[0];
                            g += imagePointer1[1];
                            r += imagePointer1[2];
                            imagePointer1 += 4;
                        }

                        //4 bytes per pixel
                        imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
                    }

                }

                image.UnlockBits(bitmapData1);

                return Color.FromArgb(r / a, g / a, b / a);
            }
            return Color.Transparent;
        }



        public Image Crop(Image bmp, Rectangle cropRect)
        {
            Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
            using (Graphics g = Graphics.FromImage(target))
            {
                g.DrawImage(bmp, new Rectangle(0, 0, target.Width, target.Height),
                                 cropRect,
                                 GraphicsUnit.Pixel);
            }
            return (Image)target;
        }



        protected static byte[] ReadBitmap2ByteArray(string fileName)
        {
            //using (Bitmap image = new Bitmap(fileName))
            //{
            //    MemoryStream stream = new MemoryStream();
            //    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //    return stream.ToArray();
            //}

            using (Image img = Image.FromFile(fileName))
            {
                byte[] arr;
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    arr = ms.ToArray();
                    return arr;
                }
            }
        }

        protected static void StoreBlob2DataBase(int AksesuarId, byte[] content1, byte[] content2)
        {
            SqlConnection con = new SqlConnection(Session.DataManager.ConnectionString);
            con.Open();
            try
            {
                // insert new entry into table
                SqlCommand insert = new SqlCommand(
                    "insert into AksesuarPhotos (AksesuarId, Photo1, Photo2) values (@id, @image1, @image2)", con);
                    //"update AksesuarPhotos set Photo2 = @image where AksesuarId = @id", con);
                    //"update AksesuarPhotos set Photo1 = @image where AksesuarId = @id", con);
                SqlParameter idParameter = insert.Parameters.Add("@id", SqlDbType.Int);
                idParameter.Value = AksesuarId;
                //imageParameter.Size = content.Length;
                SqlParameter imageParameter1 = insert.Parameters.Add("@image1", SqlDbType.Binary);
                imageParameter1.Value = content1;
                imageParameter1.Size = content1.Length;
                SqlParameter imageParameter2 = insert.Parameters.Add("@image2", SqlDbType.Binary);
                imageParameter2.Value = content2;
                imageParameter2.Size = content2.Length;
                insert.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }
        
         */
    }
}